package com.example.community.service;

import com.example.community.dto.CommentDTO;
import com.example.community.dto.UserDto;
import com.example.community.enums.CommentTypeEnum;
import com.example.community.enums.NotificationStatusEnum;
import com.example.community.enums.NotificationTypeEnum;
import com.example.community.exception.CustomizeErrorCode;
import com.example.community.exception.CustomizeException;
import com.example.community.mapper.*;
import com.example.community.model.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class CommentService {

    @Autowired
    private CommentMapper commentMapper;

    @Autowired
    private QuestionMapper questionMapper;

    @Autowired
    private QuestionExtMapper questionExtMapper;

    @Autowired
    private GiteeUserMapper giteeUserMapper;

    @Autowired
    UserMapper userMapper;

    @Autowired
    private CommentExtMapper commentExtMapper;

    @Autowired
    private NotificationMapper notificationMapper;

    public boolean deleteComment(Long id){
        Comment comment = commentMapper.selectByPrimaryKey(id);
        if (comment == null)return false;
        commentMapper.deleteByPrimaryKey(id);
        return true;
    }

    @Transactional
    public void insert(Comment comment, UserDto commentator) {
        if (comment.getParentId() == null || comment.getParentId() == 0) {
            throw new CustomizeException(CustomizeErrorCode.TARGET_PARAM_NOT_FOUND);
        }
        if (comment.getType() == null || !CommentTypeEnum.isExist(comment.getType())) {
            throw new CustomizeException(CustomizeErrorCode.TYPE_PARAM_WRONG);
        }
//        if (comment.getType().equals(CommentTypeEnum.COMMENT.getType())) {
//            // 回复评论
//            Comment dbComment = commentMapper.selectByPrimaryKey(comment.getParentId());
//            if (dbComment == null) {
//                throw new CustomizeException(CustomizeErrorCode.COMMENT_NOT_FOUND);
//            }
//
//            // 回复问题
//            Question question = questionMapper.selectByPrimaryKey(dbComment.getParentId());
//            if (question == null) {
//                throw new CustomizeException(CustomizeErrorCode.QUESTION_NOT_FOUND);
//            }
//
//            commentMapper.insert(comment);
//
//            // 增加评论数
//            Comment parentComment = new Comment();
//            parentComment.setId(comment.getParentId());
//            parentComment.setCommentCount(1);
//            commentExtMapper.incCommentCount(parentComment);
//
//            // 创建通知
//            createNotify(comment, dbComment.getCommentator(), commentator.getName(), question.getTitle(), NotificationTypeEnum.REPLY_COMMENT, question.getId());
//        }
//        else {
        // 回复问题
        Question question = questionMapper.selectByPrimaryKey(comment.getParentId());
        if (question == null) {
            throw new CustomizeException(CustomizeErrorCode.QUESTION_NOT_FOUND);
        }
        comment.setCommentCount(0);
        commentMapper.insert(comment);
        question.setCommentCount(1);
        questionExtMapper.incCommentCount(question);
        NotificationTypeEnum notificationReceiverType = null;
        if (question.getCreatorType().equals("UR")){
            notificationReceiverType = NotificationTypeEnum.REPLY_USER;
        }else if (question.getCreatorType().equals("GU")){
            notificationReceiverType = NotificationTypeEnum.REPLY_GITEE_USER;
        }
        // 创建通知
        createNotify(comment, question.getCreator(), commentator.getName(), question.getTitle(), notificationReceiverType,commentator.getUserType(), question.getId());
//        }
    }

    private void createNotify(Comment comment, Long receiver, String notifierName, String outerTitle, NotificationTypeEnum notificationType,Integer commentatorType, Long outerId) {
        if (receiver.equals(comment.getCommentator()) && notificationType.getType() == commentatorType) {
            return;
        }
        Notification notification = new Notification();
        notification.setGmtCreate(System.currentTimeMillis());
        notification.setType(notificationType.getType());
        notification.setOuterId(outerId);
        notification.setNotifier(comment.getCommentator());
        notification.setStatus(NotificationStatusEnum.UNREAD.getStatus());
        notification.setReceiver(receiver);
        notification.setNotifierName(notifierName);
        notification.setOuterTitle(outerTitle);
        notificationMapper.insert(notification);
    }

    public List<CommentDTO> listByTargetId(Long id) {
        CommentExample commentExample = new CommentExample();
        commentExample.createCriteria()
                .andParentIdEqualTo(id);
//                .andTypeEqualTo(type.getType());//过期数据
        commentExample.setOrderByClause("gmt_create desc");
        List<Comment> comments = commentMapper.selectByExample(commentExample);

        if (comments.size() == 0) {
            return new ArrayList<>();
        }
        // 获取去重的评论人
        Set<Long> giteeCommentators = comments.stream().filter(comment -> comment.getType() == 1).map(Comment::getCommentator).collect(Collectors.toSet());
        Set<Long> commentators = comments.stream().filter(comment -> comment.getType() == 2).map(Comment::getCommentator).collect(Collectors.toSet());

        List<Long> giteeUserIds = new ArrayList<>(giteeCommentators);
        List<Long> userIds = new ArrayList<>(commentators);
        List<UserDto> userDtos = new ArrayList<>();
        if (giteeUserIds.size() > 0){
            GiteeUserExample giteeUserExample = new GiteeUserExample();
            giteeUserExample.createCriteria()
                    .andIdIn(giteeUserIds);
            List<GiteeUser> giteeUsers = giteeUserMapper.selectByExample(giteeUserExample);
            for (GiteeUser giteeUser : giteeUsers) {
                UserDto userDto = UserDto.getUserDtoByGiteeUser(giteeUser);
                userDtos.add(userDto);
            }
        }
        if (userIds.size() > 0){
            UserExample userExample = new UserExample();
            userExample.createCriteria()
                    .andIdIn(userIds);
            List<User> users = userMapper.selectByExample(userExample);
            for (User user : users) {
                userDtos.add(UserDto.getUserDtoByUser(user));
            }
        }
        // 获取评论人并转换为 Map

        Map<Long, UserDto> giteeUserMap = userDtos.stream().filter(userDto -> userDto.getUserType() == 1).collect(Collectors.toMap(UserDto::getId, user -> user));
        Map<Long, UserDto> userMap = userDtos.stream().filter(userDto -> userDto.getUserType() == 2).collect(Collectors.toMap(UserDto::getId, user -> user));
        // 转换 comment 为 commentDTO
        List<CommentDTO> commentDTOS = comments.stream().map(comment -> {
            CommentDTO commentDTO = new CommentDTO();
            BeanUtils.copyProperties(comment, commentDTO);
            switch (comment.getType()) {
                case 1:
                    commentDTO.setUser(giteeUserMap.get(comment.getCommentator()));
                    break;
                case 2:
                    commentDTO.setUser(userMap.get(comment.getCommentator()));
                    break;
            }
            return commentDTO;
        }).collect(Collectors.toList());

        return commentDTOS;
    }
}
